package com.cloudbroker.bcs.platform.dav.common.util;

import com.cloudbroker.bcs.common.jres.util.JresUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestUtil {
	private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);

	/**
	 * 获取request.getParameterMap() - 每个name仅存在一个value
	 * */
	public static final <T> T getSingleParameterMapForBody(
			HttpServletRequest request , Class<?> T) {
		T param;
		try {
			param = (T) JresUtil.bodyProtocolToBean(getSingleParameterMapForBody(request) , T);
		}catch (Exception e) {
			logger.error("get single parameter map for body error " , e);
			param = (T) BeanUtils.instantiate(T);
		}
		return param;
	}

	/**
	 * 获取request.getParameterMap() - 每个name仅存在一个value
	 * */
	public static Map<String, Object> getSingleParameterMapForBody(
			HttpServletRequest request) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		Enumeration<?> nameEnumeration = request.getParameterNames();
		String name = "";
		while( nameEnumeration.hasMoreElements() ) {
			name = (String) nameEnumeration.nextElement();
			resMap.put(name, request.getParameter(name));
		}
		return resMap;
	}

	/**
	 * 获取request.getParameterMap() - 每个name仅存在一个value
	 * */
	public static Map<String, String> getSingleParameterMap(
			HttpServletRequest request) {
		Map<String, String> resMap = new HashMap<String, String>();
		Enumeration<?> nameEnumeration = request.getParameterNames();
		String name = "";
		while( nameEnumeration.hasMoreElements() ) {
			name = (String) nameEnumeration.nextElement();
			resMap.put(name, request.getParameter(name));
		}
		return resMap;
	}
	
	/**
	 * 获取request.getParameterMap() - 每个name或存在多个value
	 * */
	public static Map<String, String[]> getParameterMap(
			HttpServletRequest request) {
		Map<String, String[]> resMap = new HashMap<String, String[]>();
		Enumeration<?> nameEnumeration = request.getParameterNames();
		String name = "";
		while( nameEnumeration.hasMoreElements() ) {
			name = (String) nameEnumeration.nextElement();
			resMap.put(name, request.getParameterValues(name));
		}
		return resMap;
	}

}
